<template>
  <div>
    <!--权限校验组件  -->
    <authority-tool :authority-keys="authorityKeys" :has-authority="hasAuthority"></authority-tool>
    <a-tree
      v-if="treeData.length>0"
      ref="unitTree"
      :loadData="onLoadData"
      :treeData="treeData"
      :replaceFields="replaceFields"
      :defaultExpandedKeys="defaultSelectedKeys"
      :defaultSelectedKeys="defaultSelectedKeys"
      :checkable="checkable"
      :checkStrictly="true"
      @select="treeNodeSelect"
      @check="treeNodeCheck"
    >
      <template slot="custom" slot-scope="item">
        <span style="margin-right:10px">{{item.unitName}}</span>
        <template v-if="editTree">
          <a-icon
            v-if="hasAuthority.unitAdd"
            @click.stop="operationUnit(item,'add')"
            twoToneColor="#eb2f96"
            type="plus"
            class="unit-tree-title-icon"
            v-show="item.unitId==selectedKey && showAddBtn"
          />
          <a-icon
            @click.stop="operationUnit(item,'update')"
            type="edit"
            class="unit-tree-title-icon"
            v-if="item.parentId!=0 && hasAuthority.unitUpdate"
            v-show="item.unitId==selectedKey && showEditBtn"
          />
          <a-icon
            @click.stop="deleteUnit(item)"
            type="delete"
            class="unit-tree-title-icon"
            v-if="item.parentId!=0 && item.leaf==0 && hasAuthority.unitDelete"
            v-show="item.unitId==selectedKey && showDeleteBtn"
          />
        </template>
      </template>
    </a-tree>
    <a-modal :visible="visible" @cancel="()=>{this.visible = false}" :footer="null">
      <template slot="title">
        <a-icon type="form" />
        {{formState=="add"?'新增':'修改'}}部门
      </template>
      <unit-form
        v-if="visible"
        ref="unitForm"
        formType="dialog"
        :formState="formState"
        :currentUnitId="currentUnitId"
        @insertSuccess="insertSuccess"
        @updateSuccess="updateSuccess"
      ></unit-form>
    </a-modal>
  </div>
</template>
<script>
import { unitList, unitDelete } from "@/api/org/unit";
import UnitForm from "@/views/org/unit/form";
const customSlot = { title: "custom" };
export default {
  components: { UnitForm },
  props: {
    //显示新增按钮
    showAddBtn: {
      type: Boolean,
      default: true
    },
    //显示编辑按钮
    showEditBtn: {
      type: Boolean,
      default: true
    },
    //显示删除按钮
    showDeleteBtn: {
      type: Boolean,
      default: true
    },
    //能否编辑树
    editTree: {
      type: Boolean,
      default: true
    },
    //是否开启checkbox
    checkable: {
      type: Boolean,
      default: false
    },
    //默认禁用哪几项选择
    disableCheckbox: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      defaultSelectedKeys: [], //默认选中的key
      selectedKey: undefined, //当前选中的key
      checkedKeys: [], //checkbox选中的值
      selectedData: {}, //选中的对象
      treeData: [], //树数据
      queryParam: {}, //查询参数
      replaceFields: { children: "children", title: "unitName", key: "unitId" },
      ////////////////以下属性为部门form需要的属性
      visible: false,
      currentUnitId: undefined,
      currentNode: undefined, //当前选中的node
      formState: "", //表单状态
      ////////////////以下是权限部分///////////////////////////////////////
      authorityKeys: [
        "org:userDept:add",
        "org:userDept:update",
        "org:userDept:delete"
      ],
      hasAuthority: {
        unitAdd: false,
        unitUpdate: false,
        unitDelete: false
      }
    };
  },
  created() {
    this.getTopTreeData();
  },
  methods: {
    //得到第一级部门数据
    getTopTreeData() {
      this.queryParam.parentId = 0;
      unitList(this.queryParam).then(response => {
        const { data } = response.data;
        this.treeData = this.formatDataToTreeData(data);
        this.defaultSelectedKeys = [data[0].unitId]; //默认选中部门为第一级节点
        this.selectedData = data[0];
        this.selectedKey = data[0].unitId;
      });
    },
    //加载异步数据
    onLoadData(node) {
      if (!this.currentNode) this.currentNode = node; //设置第一级默认node
      return new Promise(resolve => {
        if (node.dataRef.children && node.dataRef.children.length > 0) {
          //如果有子集则不在进行搜索
          resolve();
          return;
        }
        this.queryParam.parentId = node.dataRef.unitId;
        unitList(this.queryParam).then(response => {
          let { data } = response.data;
          if (data && data.length > 0) {
            node.dataRef.children = this.formatDataToTreeData(data);
          } else {
            //如果查询到子集没有数据了 我们要将他改为子节点
            node.dataRef.isLeaf = true;
          }
          this.treeData = [...this.treeData];
          resolve();
        });
      });
    },
    //格式化数据库数据变成treeData需要的数据
    formatDataToTreeData(data) {
      if (!data || data.length == 0) return [];
      for (let i in data) {
        data[i].isLeaf = !(data[i].leaf && data[i].leaf > 0);
        //查看是否有叶子节点
        data[i].scopedSlots = customSlot;
        //处理禁止选中的数据
        if (this.disableCheckbox.indexOf(data[i].unitId) != -1) {
          data[i].disableCheckbox = true;
        }
      }
      return data;
    },
    //tree 选中
    treeNodeSelect(selectedKeys, info) {
      //只有在选中的时候才去做
      if (info.selected) {
        this.selectedKey = selectedKeys[0];
        this.selectedData = info.node.dataRef;
        this.currentNode = info.node;
      }
    },
    //tree checkbox选中
    treeNodeCheck(checkedKeys) {
      this.checkedKeys = checkedKeys.checked;
    },
    //新增修改部门时
    operationUnit(item, formState) {
      this.currentUnitId = item.unitId;
      this.formState = formState;
      this.visible = true;
    },
    //删除部门时
    deleteUnit(item) {
      var _self = this;
      this.$confirm({
        title: "提示",
        content: "点击确认按钮将删除部门" + item.unitName + "吗？",
        onOk() {
          unitDelete(item).then(response => {
            _self.refreshParentNode();
          });
        }
      });
    },
    //刷新当前节点
    refreshCurrentNode() {
      this.currentNode.dataRef.isLeaf = false;
      this.currentNode.dataRef.children = [];
      this.onLoadData(this.currentNode); //刷新当前node
    },
    //刷新父节点
    refreshParentNode() {
      let parentNode = this.currentNode.$parent;
      parentNode.dataRef.children = [];
      this.onLoadData(parentNode); //刷新父节点node
    },
    //新增成功
    insertSuccess() {
      this.refreshCurrentNode();
    },
    //修改成功
    updateSuccess() {
      this.refreshParentNode();
    }
  },
  watch: {
    selectedKey(val) {
      this.$emit("changeSelect", this.selectedKey, this.selectedData);
    }
  }
};
</script>
<style >
.unit-tree-title-icon {
  padding: 0 4px;
}
</style>